// Copyright 2009, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.urchin.dataapi.soap.reportservice;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This code sample
 *  - retrieves list of tables and supported dimensions and metrics for specified profile
 *  - retrieves list of dimensions and metrics for specified profile and [optional] table
 * 
 * To build and run the sample you need to download Apache Axis 1.4.1 from 
 * http://ws.apache.org/axis2/download/1_4_1/download.cgi
 * 
 * To generate the web services stubs you should run WSDL2Java from Axis bin directory: 
 * %AXIS2_HOME%/bin/wsdl2java.sh -uri http://server[:port]/services/v1/reportservice?wsdl -d adb -p com.google.urchin.dataapi.soap.reportservice -s -S .
 */

public class ReportService {
  // login information
  private static final String login = "URCHIN_LOGIN";
  private static final String password = "URCHIN_PASSWORD";

  // service arguments
  private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

  private static final int profileId = 1;
  private static final String ids = "1";
  private static Date startDate;
  private static Date endDate;
  private static final String dimensions = "u:visitor_id";
  private static final String metrics = "u:pages,u:visits";
  private static final int maxResults = 5;


  public static void main(String[] args) { 
    try {
      startDate = sdf.parse("2008-01-01");
      endDate = sdf.parse("2009-01-01");
      
      GetTableList();
      GetDataWithImplicitTable();
      GetDataFiltered();
      GetDataLimited();
      GetDataSorted();
      GetDataAggregated();
    }
    catch(Exception e) {
      e.printStackTrace(); 
    }
  }

  /*
   * Retrieve list of tables and supported dimensions/metrics
   */
  public static void GetTableList() throws Exception {
    try {
      // Set up service connection
      ReportserviceStub reportStub = new ReportserviceStub(); 
      ReportserviceStub.GetTableList tableReq = new ReportserviceStub.GetTableList();
      
      // Define parameters
      tableReq.setLogin(login);
      tableReq.setPassword(password);
      tableReq.setProfileId(profileId);
      
      // Get table list
      ReportserviceStub.GetTableListResponse tableRsp = reportStub.getTableList(tableReq);
      if (tableRsp != null){
        System.out.println("ReportService::getTableList:");
        ReportserviceStub.GetTableListResponseSequence [] responseSequence = tableRsp.getGetTableListResponseSequence();
        
        // Display tables info
        for (ReportserviceStub.GetTableListResponseSequence table : responseSequence) {
          System.out.println("table id: \"" + table.getTable().getTableId()+"\", ");

          String[] dimArray = table.getTable().getDimensions().getDimension();
          // Display the table dimensions
          System.out.println("dimensions: ");
          for(String dimension : dimArray) System.out.println(" \t\""+ dimension +"\", ");
          
          String[] metricArray = table.getTable().getMetrics().getMetric();
          // Display the table metrics
          System.out.println("metrics:");
          for(String metric : metricArray) System.out.println("\t\""+ metric +"\", ");
        }
      }
    }
    catch(ApiFaultException0 e) {
      System.out.println(e.getFaultMessage().getCode() + ": " + e.getFaultMessage().getMessage());
    }
  }

  public static void GetDataWithImplicitTable() throws Exception {
    try {
      // Set up service connection
      ReportserviceStub reportStub = new ReportserviceStub(); 
      ReportserviceStub.GetData dataReq = new ReportserviceStub.GetData();

      // Define parameters
      dataReq.setLogin(login);
      dataReq.setPassword(password);
      dataReq.setIds(ids);
      dataReq.setStartDate(startDate);
      dataReq.setEndDate(endDate);
      dataReq.setDimensions(dimensions);
      dataReq.setMetrics(metrics);
      dataReq.setMaxResults(maxResults);

      dumpArgs(dataReq);
      
      // Get data
      ReportserviceStub.GetDataResponse dataRsp = reportStub.getData(dataReq); 
      if (dataRsp != null) {
        ReportserviceStub.Data[] data = dataRsp.getRecord();

        // Display data
        for (ReportserviceStub.Data item : data) {
          System.out.println("record id: \"" + item.getRecordId() + "\", ");
          ReportserviceStub.DataDimension[] dimArray = item.getDimensions().getDimension();
          System.out.println("dimensions:");

          // Display data dimensions
          for(ReportserviceStub.DataDimension dimension : dimArray)
            System.out.println(" \tname: \"" + dimension.getName() + "\", string: " + dimension.getString());

          ReportserviceStub.DataMetrics metric = item.getMetrics();
          // Display data metrics (Pages, Visits).
          System.out.println("metrics:");
          System.out.println("\tpages: " + metric.getPages() +", visits: " + metric.getVisits());
        }
      }
    }
    catch(ApiFaultException0 e) {
      System.out.println(e.getFaultMessage().getCode() + ": " + e.getFaultMessage().getMessage());
    }
  }

  /**
   * This method retrieves data from "1" table and applies filter
   */
  public static void GetDataFiltered() throws Exception {
    try {
      // Set up service connection.
      ReportserviceStub reportStub = new ReportserviceStub(); 
      ReportserviceStub.GetData dataReq = new ReportserviceStub.GetData();

      // Define parameters.
      dataReq.setLogin(login);
      dataReq.setPassword(password);
      dataReq.setIds(ids);
      dataReq.setStartDate(startDate);
      dataReq.setEndDate(endDate);
      dataReq.setMaxResults(maxResults);
      dataReq.setDimensions("u:utm_source,u:utm_medium,u:utm_campaign");
      dataReq.setMetrics("u:pages,u:visits,u:transactions");
      dataReq.setFilters("u:utm_source=~direct,u:pages>0");

      dumpArgs(dataReq);

      // Get data
      ReportserviceStub.GetDataResponse dataRsp = reportStub.getData(dataReq); 
      if (dataRsp != null){
        ReportserviceStub.Data[] data = dataRsp.getRecord();

        // Display data
        for (ReportserviceStub.Data item : data){
          System.out.println("record id: \"" + item.getRecordId() + "\", ");
          ReportserviceStub.DataDimension[] dimArray = item.getDimensions().getDimension();

          // Display dimensions
          System.out.println("dimensions:");
          for(ReportserviceStub.DataDimension dimension : dimArray)
            System.out.println(" \tname: \"" + dimension.getName() +"\", value: " + dimension.getString());
        }
      }
    }
    catch(ApiFaultException0 e) {
      System.out.println(e.getFaultMessage().getCode() + ": " + e.getFaultMessage().getMessage());
    }
  }

  /**
   * This method retrieves visitor list limited with max-records.
   */
  public static void GetDataLimited() throws Exception {
    try {
      // Set up service connection
      ReportserviceStub reportStub = new ReportserviceStub(); 
      ReportserviceStub.GetData dataReq = new ReportserviceStub.GetData();

      // Define parameters
      dataReq.setLogin(login);
      dataReq.setPassword(password);
      dataReq.setIds(ids);
      dataReq.setStartDate(startDate);
      dataReq.setEndDate(endDate);
      dataReq.setDimensions(dimensions);
      dataReq.setMaxResults(maxResults);

      dumpArgs(dataReq);

      // Get data
      ReportserviceStub.GetDataResponse dataRsp = reportStub.getData(dataReq); 
      if (dataRsp != null){
        ReportserviceStub.Data[] data = dataRsp.getRecord();
        
        // Display data
        for (ReportserviceStub.Data item : data){
          System.out.println("record id: \"" + item.getRecordId() + "\", ");
          ReportserviceStub.DataDimension[] dimArray = item.getDimensions().getDimension();

          // Display data dimensions
          System.out.println("dimensions:");
          for(ReportserviceStub.DataDimension dimension : dimArray)
            System.out.println(" \tname: \"" + dimension.getName() + "\", string: " + dimension.getString());
        }
      }
    }
    catch(ApiFaultException0 e) {
      System.out.println(e.getFaultMessage().getCode() + ": " + e.getFaultMessage().getMessage());
    }
  }

  /**
   * This method retrieves transaction list sorted by Id (descending order)
   */
  public static void GetDataSorted() throws Exception {
    try {
      // Set up service connection
      ReportserviceStub reportStub = new ReportserviceStub(); 
      ReportserviceStub.GetData dataReq = new ReportserviceStub.GetData();

      // Define parameters
      dataReq.setLogin(login);
      dataReq.setPassword(password);
      dataReq.setIds(ids);
      dataReq.setStartDate(startDate);
      dataReq.setEndDate(endDate);
      dataReq.setMaxResults(maxResults);
      dataReq.setDimensions("u:transaction_id");
      dataReq.setMetrics("u:transactions,u:revenue");
      dataReq.setSort("-u:transactions");
      dataReq.setTable(257);

      dumpArgs(dataReq);

      // Get data
      ReportserviceStub.GetDataResponse dataRsp = reportStub.getData(dataReq);
      if (dataRsp != null){
        ReportserviceStub.Data[] data = dataRsp.getRecord();

        // Display data info
        for (ReportserviceStub.Data item : data){
          System.out.println("record id: \"" + item.getRecordId() + "\", ");
          ReportserviceStub.DataDimension[] dimArray = item.getDimensions().getDimension();

          // Display dimensions
          System.out.println("dimensions:");
          for(ReportserviceStub.DataDimension dimension : dimArray)
            System.out.println(" \tname: \"" + dimension.getName() + "\", string: " + dimension.getString());

          ReportserviceStub.DataMetrics metric = item.getMetrics();
          // Display data metrics (Ttransactions, Revenue).
          System.out.println("metrics:");
          System.out.println("\ttransactions: " + metric.getTransactions() +", revenue: " + metric.getRevenue());
        }
      }
    }
    catch(ApiFaultException0 e) {
      System.out.println(e.getFaultMessage().getCode() + ": " + e.getFaultMessage().getMessage());
    }
  }

  /**
   * This method retrieves totals aggregated by month for specific date range sorted by one metric, 
   * limited with max-records
   */
  public static void GetDataAggregated() throws Exception {
    try {
      // Set up service connection
      ReportserviceStub reportStub = new ReportserviceStub(); 
      ReportserviceStub.GetData dataReq = new ReportserviceStub.GetData();

      // Define parameters
      dataReq.setLogin(login);
      dataReq.setPassword(password);
      dataReq.setIds(ids);
      dataReq.setStartDate(startDate);
      dataReq.setEndDate(endDate);
      dataReq.setDimensions("u:month");
      dataReq.setMetrics("u:hits,u:bytes");
      dataReq.setSort("u:hits");
      dataReq.setMaxResults(maxResults);
      dataReq.setTable(258);

      dumpArgs(dataReq);

      // Get data
      ReportserviceStub.GetDataResponse dataRsp = reportStub.getData(dataReq);
      if (dataRsp != null){
        ReportserviceStub.Data[] data = dataRsp.getRecord();

        // Display data
        for (ReportserviceStub.Data item : data){
          System.out.println("record id:\"" + item.getRecordId() + "\", ");

          ReportserviceStub.DataDimension[] dimArray = item.getDimensions().getDimension();
          // Display dimensions
          System.out.println("dimensions:");
          for(ReportserviceStub.DataDimension dimension : dimArray)
            System.out.println(" \tname: \"" + dimension.getName() + "\", string: " + dimension.getString());

          ReportserviceStub.DataMetrics metric = item.getMetrics();
          // Display data metrics (Hits, Bytes)
          System.out.println("metrics:");
          System.out.println("\thits: " + metric.getHits() + ", bytes: " + metric.getBytes());
        }
      }
    }
    catch(ApiFaultException0 e) {
      System.out.println(e.getFaultMessage().getCode() + ": " + e.getFaultMessage().getMessage());
    }
  }
  
  private static void dumpArgs(ReportserviceStub.GetData dataReq) {
    if (dataReq == null) return;

    System.out.println("=====================================================");
    System.out.println("ReportService::getData:");
    System.out.println("\tlogin:\t\t" + dataReq.getLogin() + "\n\tpassword:\t*");
    System.out.println("\tids:\t\t" + dataReq.getIds());
    System.out.println("\tstartDate:\t" + dataReq.getStartDate().toString());
    System.out.println("\tendDate:\t" + dataReq.getEndDate().toString());
    System.out.println("\tdimensions:\t" + dataReq.getDimensions());
    System.out.println("\tmetrics:\t" + dataReq.getMetrics());
    System.out.println("\tstartIndex:\t" + dataReq.getStartIndex());
    System.out.println("\tmaxResult:\t" + dataReq.getMaxResults());
    System.out.println("\tfilters:\t" + dataReq.getFilters());
    System.out.println("\ttableId:\t" + dataReq.getTable());
    System.out.println("=====================================================");
  }
}
